<template>
  <div id="app">
    <h1>购物车</h1>
    
    <div v-if="cartItems.length === 0">
      购物车为空
    </div>
    
    <div v-else>
      <cart-item 
        v-for="item in cartItems" 
        :key="item.id" 
        :item="item"
      />
      
      <div class="total-price">
        总价: ¥{{ totalPrice }}
      </div>
      
      <div class="add-item-form">
        <input v-model="newItemName" placeholder="商品名称">
        <input v-model.number="newItemPrice" type="number" placeholder="价格">
        <button @click="addItem">添加商品</button>
      </div>
    </div>
  </div>
</template>

<script>
import CartItem from './components/CartItem.vue'

export default {
  name: 'App',
  components: {
    CartItem
  },
  data() {
    return {
      newItemName: '',
      newItemPrice: 0
    }
  },
  computed: {
    cartItems() {
      return this.$store.state.cartItems
    },
    totalPrice() {
      return this.$store.getters.totalPrice
    }
  },
  methods: {
    addItem() {
      if (this.newItemName && this.newItemPrice > 0) {
        const newItem = {
          id: Date.now(),
          name: this.newItemName,
          price: this.newItemPrice,
          quantity: 1
        }
        this.$store.dispatch('addItem', newItem)
        this.newItemName = ''
        this.newItemPrice = 0
      }
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.total-price {
  font-weight: bold;
  font-size: 1.2em;
  margin: 20px 0;
}

.add-item-form {
  margin-top: 20px;
}

.add-item-form input {
  margin-right: 10px;
  padding: 5px;
}
</style>